<?php
/**
 * 氪信|app风控对接
 */
namespace Home\Controller;


use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Common\Vendor\Hook\BaseHook;
use Home\Model\ConsumeHistoryModel;
use Home\Model\CreditVettingModel;
use Home\Model\FinishModel;
use Think\Controller;
use Common\Library\BusinessException;
use Common\Library\Constant;
use Think\Log;
use Common\Library\SendSMS;
use Think\Cache\Driver\Redis;

class KexinController extends Controller
{
    protected $app_key = 'bb5e9a5b64f6413b973554ee';
    protected $access_key = 'd0a72e2d9d6a4655bd460db3c074048d';

    public function __construct()
    {
        parent::__construct();
        try {
            Request::parse();//校验请求|sign值等
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }

    public function getKexinScore()
    {
        Log::kexin_write("***************************getKexinScore_Start*****************************");
        //这里暂时先注释掉，等正式了打开使用这个接口
        $user_id = I("request.user_id");
        $device_id = I("request.device_id");
        Log::kexin_write("***********". json_encode(I('request.')) ."**************");
        try {
            // $user_id = '366341';
            // $device_id = '867324021146036';

            $applicant_count = D("ConsumeHistory")->where("customer_id = $user_id and type = 4")->order("add_time desc")->find();

            $is_new_applicant = $applicant_count ? "2" : "1";//1-新贷用户，2-续贷用户，默认为1-新贷客户
            $loan_apply_date = date('Y-m-d H:i:s',$applicant_count['add_time']);//"2017-08-30 11:37:30"

            if(!$user_id){
                Log::kexin_write("没有user_id***********". json_encode(I('request.')) ."**************");
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            $customerInfo = $this->getContactsInfo($user_id);
            if (empty($customerInfo['mobile1']) || empty($customerInfo['mobile2'])) {
                $emergency_contacts = [   //可选 Array 紧急联系人数组
                    [
                        'contact_name' => $customerInfo['parent_name'],
                        'contact_number' => $customerInfo['parent_phone'],
                    ],
                    [
                        'contact_name' => $customerInfo['brothers_name'],
                        'contact_number' => $customerInfo['brothers_phone'],
                    ],
                    [
                        'contact_name' => $customerInfo['friends_name'],
                        'contact_number' => $customerInfo['friends_phone'],
                    ],
                    [
                        'contact_name' => $customerInfo['colleague_name'],
                        'contact_number' => $customerInfo['colleague_phone'],
                    ]
                ];
            } else {
                $emergency_contacts = [
                    [
                        'contact_name' => $customerInfo['name1'],
                        'contact_number' => $customerInfo['mobile1'],
                    ],
                    [
                        'contact_name' => $customerInfo['name2'],
                        'contact_number' => $customerInfo['mobile2'],
                    ]
                ];
            }
            // var_dump($customerInfo);die;
            // $callRecord = $this->callRecord($user_id);
            // var_dump($callRecord);die;
            


            $data = [
            'app_key' => $this->app_key,
            'user_id' => $user_id,
            'device_id' => $device_id,
            'application' => [
                'is_new_applicant' => $is_new_applicant, //1-新贷用户，2-续贷用户，默认为1-新贷客户
                'loan_apply_date' => $loan_apply_date,  //贷款申请时间,格式要求"2017-03-15 11:37:30"
            ],
            'basic' => [                    // 是 贷款申请用户填写的申请信息
                'mobile_number' => $customerInfo['user_mobile'], //可选 申请人手机号(可脱敏,隐去最后4位)
                'mobile_md5' => md5($customerInfo['user_mobile']),  //是 申请人手机号md5
                'user_name' => $customerInfo['user_name'],  //可选 姓名
                'identity_number' => $customerInfo['id_card_num'],  //可选 身份证号(可脱敏,隐去第13-16位)
                'emergency_contacts' => $emergency_contacts,
                // 'educational_level' => $loan_apply_date,    //可选 学历 枚举值为[研究生，本科，大专，高中，其他]
                // 'university_name' => $loan_apply_date,    //可选 毕业院校
                // 'marriage_status' => $loan_apply_date,    //可选 婚姻状况 枚举值为[未婚，已婚，离异，其他]
                // 'home_province' => $loan_apply_date,    //可选 居住省份
                // 'home_city' => $loan_apply_date,    //可选 居住城市
                // 'home_address' => $loan_apply_date,    //可选 家庭住址，省+市+区/县+详细地址，不要包含特殊字符
                // 'company_province' => $loan_apply_date,    //可选 工作省份
                // 'company_city' => $loan_apply_date,    //可选 工作城市
                // 'company_address' => $loan_apply_date,    //可选 工作地址，省+市+区/县+详细地址，不要包含特殊字符
            ],
            // 'call_log' => [             //可选 运营商授权爬取通话记录，针对ios平台借款人建议post
            //     'end_time' => $loan_apply_date,     // 是 通话记录最后抓取时间
            //     'calls' => [                        //Array 是 通话记录
            //         [
            //             'num' => $loan_apply_date,  //  是 对方号码
            //             'type' => $loan_apply_date,  //Int  是 通话类型 1-拨入，2-拨出
            //             'date' => $loan_apply_date,  //  是 通话时间，格式要求"2017-03-15 11:37:30"
            //             'duration' => $loan_apply_date,  //Float  是 通话时长(秒)
            //             'place' => $loan_apply_date,  //  是 通话发生地
            //         ],
            //         [
            //             'num' => $loan_apply_date,  //  是 对方号码
            //             'type' => $loan_apply_date,  //Int  是 通话类型 1-拨入，2-拨出
            //             'date' => $loan_apply_date,  //  是 通话时间，格式要求"2017-03-15 11:37:30"
            //             'duration' => $loan_apply_date,  //Float  是 通话时长(秒)
            //             'place' => $loan_apply_date,  //  是 通话发生地
            //         ]
            //     ],
            // ],
        ];
            Log::kexin_write("向氪信请求数据:*******" . json_encode($data) . "*******");
            
            $kexinScore = $this->kexinCurlPost($data);

            $ret = Constant::getReturn(Constant::SUCCESS);

            Log::kexin_write("氪信返回响应数据:*******" . $kexinScore . "*******");

            $kexinScore = json_decode($kexinScore,true);
            $ret['kexinScore'] = $kexinScore;
            // var_dump($ret);die;
        } catch (Exception $e) {
            Log::kexin_write("*******|抛出异常|code" . $e->getCode() . "|msg" . $e->getMessage() . "*******");
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        $ret = Response::format($ret);

        Log::kexin_write("ret:*******" . json_encode($ret) . "*******");

        $device_id_back = $ret['kexinScore']['input']['device_id'];//867922029702500
        $user_id_back = $ret['kexinScore']['input']['user_id'];
        $riskScore = $ret['kexinScore']['output']['riskScore'];
        Log::kexin_write("*********|获取氪信响应|device_id_back:" . $device_id_back . "|user_id_back:" . $user_id_back . "|riskScore:" . $riskScore . "**********");

        if ($user_id == $user_id_back && $device_id == $device_id_back) {

            $whereand[] = "id = '$user_id' ";
            array_push($whereand, " device_id = '$device_id' ");
            $where = join(' and ' , $whereand);
            
            $res = M("customer",null)->where($where)->setField(array( 'kexin_score' => $riskScore ));
            // var_dump($res);die;
            
            Log::kexin_write("*********获取氪信分后入库Customer结果|" . $res . "|1成功0未修改_入库失败**********");
            Log::kexin_write("*********氪信分入库Customer操作时间|" . date("Y-m-d H:i:s", time()) . "|**********");
        } else {
            Log::kexin_write("请求与返回数据不匹配*********|user_id|" . $user_id . "|device_id|" . $device_id . "|user_id_back|" . $user_id_back . "|device_id_back|" . $device_id_back . "|**********");
        }
        // var_dump($ret);die;
        Log::kexin_write("***************************getKexinScore_End*****************************");
        $this->ajaxReturn($ret);
    }
    //用户通话记录列表
    function callRecord($customerId)
    {
        if($customerId){
            //用户手机通讯录
            $Contact = D('CustomerContact');
            // $lists = $Contact->where(["customer_id"=>$customerId])->field("contact_phone,contact_name")->select();
            // foreach ($lists as $k=>$v){
            //     $lists[$k]['contact_phone'] = str_replace("-","",$v['contact_phone']);
            //     if(str_replace("-","",$v['contact_phone']) == $v['contact_phone']){
            //         $lists[$k]['contact_phone'] = str_replace(" ","",$v['contact_phone']);
            //         if(str_replace(" ","",$v['contact_phone'])== $v['contact_phone']){
            //             $lists[$k]['contact_phone'] = str_replace("+86","",$v['contact_phone']);
            //         }
            //     }
            // }
            //用户紧急联系人
            $extra_info = D("CustomerExtraInfo")->where("customer_id = ".$customerId)->field("parent_name,parent_phone,brothers_name,brothers_phone,friends_name,friends_phone,colleague_name,colleague_phone")->select();
            $extra_info = $extra_info[0];
            //获取token值
            $Model = D('Customer');
            $sql = "SELECT cd.trade_no FROM certificate_data cd  JOIN customer c ON c.real_name=cd.name and c.mobile=cd.mobile WHERE cd.data_type=2  AND c.id = ".$customerId." ORDER BY cd.id DESC LIMIT 1";
            $arr_id = $Model->query($sql);
            $token = $arr_id[0]['trade_no'];
            Log::write("通话token：".$token,Log::DEBUG);
            $behave = $arr = $contacts = $flag = $del = $del1 = $urgent = $list0 = array();

            //远程抓取所有信息
            $str_all = file_get_contents("http://api.huoyanzichan.com/Home/Hulushuju/getReport?token=".$token);
            $str_all = substr($str_all,strpos($str_all,'{'));
            $arr_data = array('customer_token' => $token, 'report_content' => $str_all);
            $url = "http://admin.huoyanzichan.com/index.php?g=Dataapi&m=ReportData&a=intodb_dhb";
            // $this->request_post($url, $arr_data);

            $arr_all = json_decode($str_all);
            $data = $arr_all->data;

            $contact_list = $data->contact_list;//通讯详单
            // var_dump($contact_list);die;
            foreach($contact_list as $arr2){
                $flag[]=$arr2->call_cnt;
            }
           // array_multisort($flag, SORT_DESC, $contact_list);
            foreach ($contact_list as $k=>$v){
                $contacts[$k]['phone_num']=$v->phone_num;
                $contacts[$k]['needs_type']=$v->needs_type;
                $contacts[$k]['phone_num_loc']=$v->phone_num_loc;
                $contacts[$k]['call_cnt']=$v->call_cnt;
                $contacts[$k]['call_len']=ceil($v->call_len);
                $contacts[$k]['call_out_cnt']=$v->call_out_cnt;
                $contacts[$k]['call_in_cnt']=$v->call_in_cnt;
                $contacts[$k]['call_in_len']=ceil($v->call_in_len);
                $contacts[$k]['call_out_len']=ceil($v->call_out_len);
            }
            $contacts = array_values($contacts);
            //紧急联系人,400,0开头的号码置顶
            if($contacts) {
                $urgent[0]['phone_num'] = $extra_info['parent_phone']. "&nbsp;<font color=red>(父母)</font>";
                $urgent[1]['phone_num'] = $extra_info['brothers_phone']. "&nbsp;<font color=red>(直系)</font>";
                $urgent[2]['phone_num'] = $extra_info['friends_phone']. "&nbsp;<font color=red>(朋友)</font>";
                $urgent[3]['phone_num'] = $extra_info['colleague_phone']. "&nbsp;<font color=red>(同事)</font>";
            }
            foreach ($contacts as $k=>$vs){
                if($vs['phone_num']==$extra_info['parent_phone']){
                    $urgent[0]['needs_type'] = $contacts[$k]['needs_type'];
                    $urgent[0]['phone_num_loc'] = $contacts[$k]['phone_num_loc'];
                    $urgent[0]['call_len'] = $contacts[$k]['call_len'];
                    $urgent[0]['call_cnt'] = $contacts[$k]['call_cnt'];
                    $urgent[0]['call_out_cnt'] = $contacts[$k]['call_out_cnt'];
                    $urgent[0]['call_in_cnt'] = $contacts[$k]['call_in_cnt'];
                    $urgent[0]['call_in_len'] =$contacts[$k]['call_in_len'];
                    $urgent[0]['call_out_len'] =$contacts[$k]['call_out_len'];
                }elseif ($vs['phone_num']==$extra_info['brothers_phone']){
                    $urgent[1]['needs_type'] = $contacts[$k]['needs_type'];
                    $urgent[1]['phone_num_loc'] = $contacts[$k]['phone_num_loc'];
                    $urgent[1]['call_len'] = $contacts[$k]['call_len'];
                    $urgent[1]['call_cnt'] = $contacts[$k]['call_cnt'];
                    $urgent[1]['call_out_cnt'] = $contacts[$k]['call_out_cnt'];
                    $urgent[1]['call_in_cnt'] = $contacts[$k]['call_in_cnt'];
                    $urgent[1]['call_in_len'] =$contacts[$k]['call_in_len'];
                    $urgent[1]['call_out_len'] =$contacts[$k]['call_out_len'];
                }elseif ($vs['phone_num']==$extra_info['friends_phone']){
                    $urgent[2]['needs_type'] = $contacts[$k]['needs_type'];
                    $urgent[2]['phone_num_loc'] = $contacts[$k]['phone_num_loc'];
                    $urgent[2]['call_len'] = $contacts[$k]['call_len'];
                    $urgent[2]['call_cnt'] = $contacts[$k]['call_cnt'];
                    $urgent[2]['call_out_cnt'] = $contacts[$k]['call_out_cnt'];
                    $urgent[2]['call_in_cnt'] = $contacts[$k]['call_in_cnt'];
                    $urgent[2]['call_in_len'] =$contacts[$k]['call_in_len'];
                    $urgent[2]['call_out_len'] =$contacts[$k]['call_out_len'];
                }elseif ($vs['phone_num']==$extra_info['colleague_phone']){
                    $urgent[3]['needs_type'] = $contacts[$k]['needs_type'];
                    $urgent[3]['phone_num_loc'] = $contacts[$k]['phone_num_loc'];
                    $urgent[3]['call_len'] = $contacts[$k]['call_len'];
                    $urgent[3]['call_cnt'] = $contacts[$k]['call_cnt'];
                    $urgent[3]['call_out_cnt'] = $contacts[$k]['call_out_cnt'];
                    $urgent[3]['call_in_cnt'] = $contacts[$k]['call_in_cnt'];
                    $urgent[3]['call_in_len'] =$contacts[$k]['call_in_len'];
                    $urgent[3]['call_out_len'] =$contacts[$k]['call_out_len'];
                }
                if(substr($vs['phone_num'],0,1)=='4'){
                    $del[$k]['phone_num'] =  $contacts[$k]['phone_num'];
                    $del[$k]['needs_type'] = $contacts[$k]['needs_type'];
                    $del[$k]['phone_num_loc'] = $contacts[$k]['phone_num_loc'];
                    $del[$k]['call_len'] = $contacts[$k]['call_len'];
                    $del[$k]['call_cnt'] = $contacts[$k]['call_cnt'];
                    $del[$k]['call_out_cnt'] = $contacts[$k]['call_out_cnt'];
                    $del[$k]['call_in_cnt'] = $contacts[$k]['call_in_cnt'];
                    $del[$k]['call_in_len'] =$contacts[$k]['call_in_len'];
                    $del[$k]['call_out_len'] =$contacts[$k]['call_out_len'];
                    unset($contacts[$k]);
                }
                if(substr($vs['phone_num'],0,1)=='0'){
                    $del1[$k]['phone_num'] =  $contacts[$k]['phone_num'];
                    $del1[$k]['needs_type'] = $contacts[$k]['needs_type'];
                    $del1[$k]['phone_num_loc'] = $contacts[$k]['phone_num_loc'];
                    $del1[$k]['call_len'] = $contacts[$k]['call_len'];
                    $del1[$k]['call_cnt'] = $contacts[$k]['call_cnt'];
                    $del1[$k]['call_out_cnt'] = $contacts[$k]['call_out_cnt'];
                    $del1[$k]['call_in_cnt'] = $contacts[$k]['call_in_cnt'];
                    $del1[$k]['call_in_len'] =$contacts[$k]['call_in_len'];
                    $del1[$k]['call_out_len'] =$contacts[$k]['call_out_len'];
                    unset($contacts[$k]);
                }
            }
            $contacts = array_merge($del1,$contacts);
            $contacts = array_merge($del,$contacts);
            $contacts = array_merge($urgent,$contacts);

            // foreach ($lists as $k=>$v){
            //     if($v['contact_phone']==$extra_info['parent_phone'] ) {
            //         $list0[0]['contact_phone'] = $extra_info['parent_phone'];
            //         $list0[0]['contact_name'] = $extra_info['parent_name']."<font color=red>(紧急联系人：父母)</font>";
            //     }elseif($v['contact_phone']==$extra_info['brothers_phone'] ){
            //         $list0[1]['contact_phone'] = $extra_info['brothers_phone'];
            //         $list0[1]['contact_name'] = $extra_info['brothers_name']."<font color=red>(紧急联系人：直亲)</font>";
            //     }elseif($v['contact_phone']==$extra_info['friends_phone'] ){
            //         $list0[2]['contact_phone'] = $extra_info['friends_phone'];
            //         $list0[2]['contact_name'] = $extra_info['friends_name']."<font color=red>(紧急联系人：朋友)</font>";
            //     }elseif($v['contact_phone']==$extra_info['colleague_phone'] ){
            //         $list0[3]['contact_phone'] = $extra_info['colleague_phone'];
            //         $list0[3]['contact_name'] = $extra_info['colleague_name']."<font color=red>(紧急联系人：同事)</font>";
            //     }
            // }

            // $lists = array_merge($list0,$lists);
            //通讯录详情匹配通话详单
            /*$res = array_intersect($contacts,$lists);
            Log::write("合集：".json_encode($res),Log::DEBUG);*/
            // foreach ($contacts as $keys=>$value) {
            //     $con[$keys]=$value['phone_num'];
            // }

           // foreach ($lists as $ke=>$va){
           //     $keys = array_search($va['contact_phone'],$con);
           //     if($keys>0){
           //        $lists[$ke]['is_call'] = '是';
           //        $lists[$ke]['call_cnt'] = $contacts[$keys]['call_cnt'];
           //        $lists[$ke]['call_len'] = $contacts[$keys]['call_len'];
           //     }else{
           //        $lists[$ke]['is_call'] = '否';
           //        $lists[$ke]['call_cnt'] = 0;
           //        $lists[$ke]['call_len'] = 0;
           //     }
           // }

            $application_check  = $arr;
            $behavior_check = $behave;
            return $contacts;
            // $this->assign('contact_list',$contacts);
            // $this->assign('lists',$lists);///////////////////////////
            // $this->display("callrecord");
        }else{
            $this->error('数据传入失败！');
        }
    }
    /*** 获取用户的附加信息 ***/
    public function getContactsInfo($customer_id)
    {
        // try{
            $cur = D('Customer')->has(['id'=>$customer_id]);
            $res = M('CustomerExtraInfo')->order('id desc')->where(['customer_id'=>$customer_id])->find();
            $res['user_mobile'] = $cur['mobile'];
            $res['user_name'] = $cur['real_name'];
            $res['id_card_num'] = $cur['id_num'];
            //校验用户是否存在未完成的订单数据或者待还款的数据
            $chk = M('ConsumeHistory')->where(['customer_id'=>$customer_id, 'status'=>['in', '1,2,4,8']])->find();
            if($chk){
                $res['is_can_change'] = 0;
            }else{
                $res['is_can_change'] = 1;
            }
            unset($res['id']);
            unset($res['customer_id']);
            unset($res['update_time']);
            // $ret = Constant::getReturn(Constant::SUCCESS);
            $ret = $res;
        // }catch (BusinessException $e){
        //     $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        // }

        $ret = Response::format($ret);
        return $ret;
        // $this->ajaxReturn($ret);
    }
    private function kexinCurlPost($data)
    {
        
        /** API签名获取 按照RFC2104的定义，使用access_key作为密钥对待签名的字符串计算 HMAC-SHA1认证码，并用Base64编码，即得到签名值 */
        $url = 'https://blp.creditx.com';
        $r = uniqid();
        $apiPath = '/xbehavior_risk_score';
        $payload = json_encode($data);
        $signString = 'POST' . '|' . $apiPath . '|' . $r . '|' . $payload;
        $sigBytes = hash_hmac("sha1", $signString, $this->access_key, true);
        $sig = urlencode(base64_encode($sigBytes));
        $url = $url . $apiPath . '?r=' . $r . '&sig=' . $sig;

        Log::kexin_write("***************************kexinCurlPost_Start*****************************");
        Log::kexin_write("url:*******" . $url . "*******data:" . json_encode($data));

        // $header = ["Content-type" => "application/json"];
        $header[] = "Content-Type: application/json;charset=utf-8";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//TRUE 将curl_exec()获取的信息以字符串返回，而不是直接输出。

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置 HTTP 头字段的数组。格式： array('Content-type: text/plain', 'Content-length: 100')
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//FALSE 禁止 cURL 验证对等证书（peer's certificate）。要验证的交换证书可以在 CURLOPT_CAINFO 选项中设置，或在 CURLOPT_CAPATH中设置证书目录。

        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        $result = curl_exec($ch);
        if(curl_errno($ch))
        {
            Log::kexin_write("(curl_errno(ch):" . curl_errno($ch) ."**************curl_error(ch):" . curl_error($ch));
            print curl_error($ch);
        }
        curl_close($ch);

        Log::kexin_write("result:*******" . $result . "*******");
        $resultArr = json_decode($result, true);
        Log::kexin_write("***************************kexinCurlPost_End*****************************");
        return $result;
        // print($result);
    }
}